package dao

import (
	"log"
	"testhttp/datasource"
	"testhttp/model"
)

func InsertGoods(goods []model.Goods) (int64, error) {
	affected, err := datasource.InstanceMaster().Insert(goods)
	log.Printf("Success! %d records insert.\n", affected)
	if err != nil {
		log.Print("Error InsertGoods():", err)
	}
	return affected, err
}

func GetGoods(id int) []model.Goods {
	res := make([]model.Goods, 0)

	err := datasource.InstanceMaster().Where("id =?", id).Find(&res)
	if err != nil {
		log.Print("Error ViewGoods():", err)
	}

	return res
}

func UpdateGoods(goods []model.Goods) int {
	var success int
	for x := 0; x < len(goods); x++ {
		// log.Print("Debug uid:", dealer[x].id)
		affected, err := datasource.InstanceMaster().ID(goods[x].Id).Update(goods[x])

		if err != nil {
			log.Print("Error UpdateGoods():", err)
		} else {
			log.Printf("%d records updated.\n", affected)
			success++
		}
	}
	return success
}

func CountGoods(param model.SelectGoods) int64 {
	uniq := new(model.Goods)
	count, err := datasource.InstanceMaster().Where(param.Where, 0).Count(uniq)
	if err != nil {
		log.Print("Error ListGoods():", err)
	}
	return count
}

func SelectGoods(param model.SelectGoods) ([]model.Goods, error) {
	res := make([]model.Goods, 0)
	offset := (param.Page - 1) * param.Pagesize
	err := datasource.InstanceMaster().Where(param.Where, 0).Limit(param.Pagesize, offset).Find(&res)
	return res, err
}
